package com.example.Utils;

import org.springframework.http.MediaType;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 输入流工具类
 * 浏览器支持预览媒体类型工具类
 */
public class InputStreamUtils {
    /**
     * InputStream转byte数组
     *
     * @param inputStream 输入流
     * @return 字节数组
     */
    public static byte[] inputStreamToByte(InputStream inputStream) throws IOException {
        // 利用内存流将全部内容写入内存
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int rc;
        while ((rc = inputStream.read()) != -1) {
            baos.write(buff, 0, rc);
        }
        return baos.toByteArray();
    }

    /**
     * 支持浏览器预览行为
     *
     * @param suffix 文件后缀
     * @return 媒体类型
     */
    public static MediaType getMediaType(String suffix) {
        MediaType mediaType;
        switch (suffix) {
            case "png":
                mediaType = MediaType.IMAGE_PNG;
                break;
            case "jpg":
            case "jpeg":
                mediaType = MediaType.IMAGE_JPEG;
                break;
            case "gif":
                mediaType = MediaType.IMAGE_GIF;
                break;
            case "pdf":
                mediaType = MediaType.APPLICATION_PDF;
                break;
            default:
                mediaType = MediaType.APPLICATION_OCTET_STREAM;
        }
        return mediaType;
    }
}
